<?php
// +----------------------------------------------------------------------
// | Author; sam
// +----------------------------------------------------------------------
namespace Sam;

use think\Db;
use Sam\SamCache;
use \think\Hook;
use think\Validate;

class Account
{
    function __construct()
    {

    }

    private $register_type = '';
    public $error = '';

    public static $third_login_type = array(
        'qq' => 1,
        'weixin' => 2,
        'weibo' => 3
    );
    public static $default_avatar = HOME_HOST . '/static/index/images/user/icon.jpg';

    /**
     * 写入cookie loginToken
     */
    public function setLoginToken($id, $time = 0)
    {
        if (!$id) {
            $this->error = 'id错误';
            return false;
        }
        $root_host = urlToRootDomain($_SERVER['HTTP_HOST']);//获取根域

        if ($time == 0) {
            $token = $this->createLoginToken($id, $time + 3600 * 24);
        } else {
            $token = $this->createLoginToken($id, $time);
        }
        if ($token === false) {
            return false;
        }
        if ($time == 0) {
            setcookie("znn_token", $token, 0, '/', $root_host, null, true);//关闭浏览器过期
        } else {
            setcookie("znn_token", $token, time() + $time + 3600, '/', $root_host, null, true);
        }
        return true;
    }

    /**
     * 删除cookie loginToken
     */
    public function delLoginToken()
    {
        $root_host = urlToRootDomain($_SERVER['HTTP_HOST']);//获取根域
        setcookie("znn_token", '', time() - 3600, '/', $root_host, null, true);
        return true;
    }


    public function createLoginToken($id, $time = 3600)
    {
        /* $member = Db::name('member')
             ->where('id', $id)
             //  ->where('status', 1)
             ->find();*/

        $member['status'] = 1;

        if (!$member) {
            $this->error = '用户不存在';
            return false;
        } else if ($member['status'] != 1) {
            $this->error = '抱歉，您的账号被禁用了.';
            return false;
        }

        $expiry_time = time() + $time;
        $os = get_os();
        $browser = get_browsername();
        $user_agent = $os . '-' . $browser;
        $token = md5($id . $expiry_time . $user_agent);
        $znn_token = $id . '|' . $expiry_time . '|' . $token;
        return $this->pri_encrypt($znn_token);
    }

//私钥加密
    public function pri_encrypt($data)
    {
        $result = '';
        $private_key = file_get_contents(APP_PATH . '/Certificate/private_key.pem');
        // $pri_key = openssl_pkey_get_private($private_key);
        openssl_private_encrypt($data, $result, $private_key);//私钥加密
        $result = base64_encode($result);
        return $result;
    }

//公钥解密
    public function pub_decrypt($data)
    {
        $result = '';
        $public_key = file_get_contents(APP_PATH . '/Certificate/public_key.pem');
        //$pub_key = openssl_pkey_get_public($public_key);
        $data = base64_decode($data);
        openssl_public_decrypt($data, $result, $public_key);//公钥解密
        return $result;
    }

    /**
     * 解密loginToken
     */
    public function decryptLoginToken($token)
    {
        if (!$token) {
            return false;
        }
        $data = $this->pub_decrypt($token);
        $data = explode('|', $data);
        if (count($data) != 3) {
            return false;
        }
        list($id, $expiry_time, $token) = $data;
        if (!$id || !$expiry_time || $expiry_time < time() || !$token) {
            return false;
        }
        $os = get_os();
        $browser = get_browsername();
        $user_agent = $os . '-' . $browser;
        if ($token != md5($id . $expiry_time . $user_agent)) {
            return false;
            /* if ($browser == 'ie') {
                 $user_agent = $os . '-chrome';
                 if ($token != md5($id . $expiry_time . $user_agent)) {
                     return false;
                 }
             } elseif ($browser == 'chrome') {
                 $user_agent = $os . '-ie';
                 if ($token != md5($id . $expiry_time . $user_agent)) {
                     return false;
                 }
             } else {
                 return false;
             }*/
        }
        return $id;
    }


    /**第三方登录 */
    public function third_login($login)
    {

    }

    /** 第三方登录注册 */
    public function thirdRegister($type, $third_info, $user)
    {

    }


    /*
    *zwj  记录登录次数、登录ip 、登录时间
    */
    public static function login_log($id, $logintype = 'email')
    {
        //$logintype = email | wechat | qq  | weibo
        $ip = get_client_ip();
        $ip_int = ip2long($ip);
        $time = time();
        Db::name('member')->where('id', $id)->setInc('login', 1);

        $log = array(
            'member_id' => $id,
            'login_time' => $time,
            'login_ip' => $ip_int,
            'origin' => $logintype
        );

        Db::name('login_log')->insert($log);
    }

    /**
     * 获取帐号类型
     * @param  [type] $account [description]
     * @return [type]          [description]
     */
    public function account_type($account)
    {
        switch (true) {
            case preg_match("/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/", $account) :
                return 'email';
                break;
            case preg_match("/^1\d{10}$/", $account) :
                return 'phone';
                break;
            default:
                return 'nickname';
                break;
        }
    }


    public function getidByOpenid($type, $openid)
    {
        $id = Db::name('openid')
            ->where('type', $type)
            ->where('openid', $openid)
            ->value('id');
        return $id;
    }

    public function getidByPhone($account)
    {
        return $exist = Db::name('member')
            ->where('phone', $account)
            ->value('id');
    }


    public function getidByEmail($account)
    {
        return $exist = Db::name('member')
            ->where('email', $account)
            ->value('id');
    }


    public function getPhoneById($id)
    {
        return $exist = Db::name('member')
            ->where('id', $id)
            ->value('phone');
    }


    /**
     * 通过帐号获取用户id
     */
    public function getidByAccount($account)
    {
        switch ($this->account_type($account)) {
            case 'phone':
                return $this->getidByPhone($account);
                break;
            case 'email':
                return $this->getidByEmail($account);
                break;
        }
    }


    /**
     * 验证密码
     */
    public function verifyPwd($id, $password)
    {
        if (!$id) {
            return false;
        }
        $info = $user = Db::name('member')
            ->field('password,status')
            ->where('id', $id)
            ->find();
        if ($info['password'] == znn_pwd_encrypt($password)) {
            return true;
        }
        return false;
    }


    public function update($date)
    {
        if (empty($date['id'])) {
            $this->error = "缺少用户id";
            return false;
        }
        $bool = Db::name('member')->update($date);
        if ($bool) {
            return true;
        }
        $this->error = "信息未改动";
        return false;
    }


    /**
     * 修改密码
     */
    public function editPwd($id, $password)
    {
        if (!$id || !$password) {
            return false;
        }
        $info = Db::name('member')
            ->where('id', $id)
            ->update(['password' => znn_pwd_encrypt($password)]);
        if ($info === false) {
            return false;
        }
        $info = Db::name('member')
            ->where('id', $id)
            ->find();
        SamCache::data('login_pwd_err_count', $info['phone'], null);
        return true;
    }


    /**手机注册 */
    public function phoneRegister($phone, $user)
    {
        $nickname = $user['nickname'];
        unset($user['nickname']);

        $user = array_merge(
            $this->baseRegisterInfo($nickname),
            $user
        );

        $this->register_type = 'phone';

        /**后期考虑分表 */
        $user['phone'] = $phone;
        /** end */
        $id = $this->addUser($user);

        return $id;

    }


    /**添加用户 */
    public function addUser($user)
    {
        if (isset($user['password'])) {
            $user['password'] = znn_pwd_encrypt($user['password']);
        }

        $user['register_type'] = $this->getLabel(array(
            $this->register_type
        ), '|');
        return Db::name('member')->insertGetId($user);
    }

    public function getLabel($data, $glue = '')
    {
        $temp = Factory::sourceLabel();

        if ($temp) {
            $data = array_merge($temp, $data);
        }

        if ($glue != '') {
            return implode($glue, $data);
        }
        return $data;
    }

    /**
     * 获取注册基本信息
     */
    public function baseRegisterInfo($nickname = '')
    {
        $user = [];
        $ip = get_client_ip();
        $ip_int = ip2long($ip);
        $now_time = time();

        $nickname = $this->verifyNickNameOrCreate($nickname);

        $user = array(
            'nickname' => $nickname,
            'reg_time' => $now_time,
            'reg_ip' => $ip_int,
            'last_login_time' => $now_time,
            'last_login_ip' => $ip_int,
            'picture' => self::$default_avatar,
            'status' => 1,
        );
        return $user;
    }

    /**验证昵称 */
    public function verifyNickNmae($nickname)
    {
        if (!$this->verifyData(array('nickname' => $nickname))) {
            return false;
        }

        if (Db::name('member')->where('nickname', $nickname)->count() > 0) {
            $this->error = '该昵称已存在，请修改重试';
            return false;
        }

        return true;
    }

    /** 生成昵称 */
    public function initNickName()
    {
        $nickname = '用户' . mt_rand(100000, 999999);
        return $nickname;
    }

    /**验证昵称，不通过则生成新的昵称*/
    public function verifyNickNameOrCreate($nickname = '')
    {
        if (!$nickname) {
            $nickname = $this->initNickName();
        }
        while (!$this->verifyNickNmae($nickname)) {
            $nickname = $this->initNickName();
        }
        return $nickname;
    }


    //快速注册
    public function fastPhoneRegister($phone)
    {
        $user = $this->baseRegisterInfo();
        $id = $this->phoneRegister($phone, $user);
        return $id;
    }

    /**验证数据*/
    public function verifyData($data)
    {
        $rule = array(
            'phone' => '/^1[3456789]{1}\d{9}$/',
            'nickname' => '/^(?![0-9]+$)[\x{4e00}-\x{9fa5}0-9a-zA-z-_]{2,11}$/u',
            'password' => '/^(?![0-9]+$)(?![a-zA-Z]+$)[0-9a-zA-Z]{6,16}$/',
            'email' => '/^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/',
        );
        $msg = array(
            'phone' => '手机格式错误',
            'nickname' => '昵称为2~11位字符，不能为纯数字或纯符号',
            'password' => '请输入6-16位数字、字母的组合密码',
            'email' => '邮箱格式错误',
        );
        $validate = Validate::make($rule, $msg);
        if (!$validate->check($data)) {
            $this->error = $validate->getError();
            return false;
        }

        return true;
    }
}